// pages/packagePurchase/packagePurchase.js
const app = getApp()
Page({
  data: {
    packageId: '', // 套餐ID
    packageInfo: {}, // 套餐信息
	isAgreed: false,
	selectedCoupon: null,
	showOrderModal: false, // 是否显示下单弹窗
	    contactInfo: {
	      name: '',
	      phone: '',
	      remark: ''
	    },
	    isFormValid: false // 表单是否有效
  },

  onLoad(options) {
    this.setData({ packageId: options.id });
    this.loadPackageInfo();
  },

  // 加载套餐信息
  loadPackageInfo() {
	var that = this
    app.util.request({
	   url: 'Kangyang/packagedetail',
	   data: {
		   id:that.data.packageId
	   },
	   success(res) {
		   var data = res.data.data;
		   console.log(data)
			that.setData({
			   packageInfo: data
			 });
		   }
	   })
  },
toggleAgreement(e) {
  this.setData({ isAgreed: e.detail.value.includes('agree') });
},

viewAgreement() {
  wx.navigateTo({
    url: '/vp_pz/pages/index/html?cmd=page&id=2'
  });
},
selectCoupon() {
  wx.navigateTo({
    url: `/pages/couponList/couponList?packageId=${this.data.packageId}`
  });
},

// 修改价格显示逻辑
computedPrice() {
  let price = this.data.packageInfo.price;
  if (this.data.selectedCoupon) {
    price = Math.max(0, price - this.data.selectedCoupon.value);
  }
  return price;
},
// 打开下单弹窗
  openOrderModal() {
    this.setData({ showOrderModal: true });
  },

  // 关闭下单弹窗
  closeOrderModal() {
    this.setData({ showOrderModal: false });
  },
  // 表单输入处理
    onNameChange(e) {
      this.setData({
        'contactInfo.name': e.detail.value
      }, this.checkFormValidity);
    },
  
    onPhoneChange(e) {
      this.setData({
        'contactInfo.phone': e.detail.value
      }, this.checkFormValidity);
    },
  
  
    onRemarkChange(e) {
      this.setData({
        'contactInfo.remark': e.detail.value
      });
    },
  
    // 检查表单有效性
    checkFormValidity() {
      const { name, phone } = this.data.contactInfo;
      const isValid = name.trim().length > 0 && /^1[3-9]\d{9}$/.test(phone);
      this.setData({ isFormValid: isValid });
    },
  // 处理购买
  handlePurchase() {
	  if (!this.data.isAgreed) {
	      wx.showToast({
	        title: '请先阅读并同意协议',
	        icon: 'none'
	      });
	      return;
	    }
	  this.openOrderModal();
  },
  // 提交订单
    submitOrder() {
      if (!this.data.isFormValid) return;
      
      wx.showLoading({ title: '提交中...' });
      
      const orderData = {
        packageId: this.data.packageId,
        packageName: this.data.packageInfo.name,
        price: this.data.packageInfo.price,
        contactInfo: this.data.contactInfo,
        createTime: new Date().toISOString()
      };
      
      console.log('提交订单数据:', orderData);
      
	  let jsonData = JSON.stringify(orderData);
	  // todo 提交医护上门申请API调用
	  app.util.request({
	  	url: 'Kangyang/placeorder',
	  	data: jsonData,
	  	method:'POST',
	  	headers: {
	  		'Content-Type': 'application/json',
	  	},
	  	success(res) {
	  		console.log(res)
			wx.hideLoading();
	  		var order_id=res.data.data.order_id;
			  var pay_params=res.data.data.pay_params;
  
			  wx.requestPayment({
				  'timeStamp': pay_params.timeStamp,
				  'nonceStr': pay_params.nonceStr,
				  'package': pay_params.package,
				  'signType': 'MD5',
				  'paySign': pay_params.paySign,
				  'success': function (resp) {
						 wx.navigateTo({
						   url: `/vp_pz/pages/order/index`
						 });
				  },
				  'fail': function (res) {
						wx.showToast({ title: '支付失败', icon: 'none' })
				  }
			  })
	  	}
	  })
      
    }
});